package com.stox.services.data.provider.manager.impl;

import java.util.Date;
import java.util.List;

import com.stox.services.data.downloader.bse.BseScripDataDownloader;
import com.stox.services.data.provider.manager.BarManager;
import com.stox.services.data.provider.repository.BarRepository;
import com.stox.shared.core.model.Bar;
import com.stox.shared.core.model.enumeration.BarSpan;
import com.stox.shared.core.model.filter.BarCriteria;

public class BarManagerImpl implements BarManager {

	public static final BarManagerImpl INSTANCE = new BarManagerImpl();
	
	private BarManagerImpl() {
		
	}
	
	@Override
	public Bar getLast(Long scripId, BarSpan barSpan) {
		return BseScripDataDownloader.INSTANCE.download(scripId, barSpan);
	}
	
	@Override
	public List<Bar> find(BarCriteria barCriteria) {
		if(null == barCriteria){
			return null;
		}
		barCriteria.validate();
		return findByScripId(barCriteria.getScripId(), barCriteria.getBarSpan(), barCriteria.getTo(), barCriteria.getFrom());
	}
	
	@Override
	public List<Bar> findByScripId(Long scripId) {
		return BarRepository.INSTANCE.findByScripId(scripId);
	}

	@Override
	public List<Bar> findByScripId(Long scripId, int count) {
		return BarRepository.INSTANCE.findByScripId(scripId, count);
	}

	@Override
	public List<Bar> findByScripId(Long scripId, Date start) {
		return BarRepository.INSTANCE.findByScripId(scripId, start);
	}

	@Override
	public List<Bar> findByScripId(Long scripId, Date start, Date end) {
		return BarRepository.INSTANCE.findByScripId(scripId, start, end);
	}

	@Override
	public List<Bar> findByScripId(Long scripId, BarSpan spanType, Date start,
			Date end) {
		return BarRepository.INSTANCE.findByScripId(scripId, spanType, start, end);
	}

	@Override
	public List<Bar> findByScripId(Long scripId, BarSpan spanType, Date start,
			int count) {
		return BarRepository.INSTANCE.findByScripId(scripId, spanType, start, count);
	}

	public List<Bar> findByScripId(Long scripId, BarSpan barSpan, Integer offset, Integer count){
		return BarRepository.INSTANCE.findByScripId(scripId, barSpan, offset, count);
	}
	
	@Override
	public void save(List<Bar> bars) {
		for(Bar bar : bars){
			BarRepository.INSTANCE.save(bar);
		}
	}
	
	@Override
	public void flush() {
		BarRepository.INSTANCE.flush();
	}
}
